//
//  NetworkUtils.swift
//  MyRanger
//
//  Created by Armstrong Liu on 2018/5/23.
//  Copyright © 2018 Everbridge. All rights reserved.
//

import Foundation

enum APIResponse {
    case failure(error: String)
    case success(data: Data)
}
typealias APICompletion = (APIResponse) -> ()

class NetworkUtils {
    static let sharedInstance = NetworkUtils()
    public var basePath = "http://10.24.32.136:7080"
    
    func fetchData(withContextPath contextPath:String, withParameters parameters:[String: String], completion:@escaping APICompletion) {
        let request = self.request(withContextPath: contextPath, withParameters: parameters)
        URLSession.shared.dataTask(with: request) { (responseData, response, error) in
            guard let data = responseData, error == nil else {
                completion(.failure(error: error!.localizedDescription))
                return
            }
            
            completion(.success(data: data))
        }.resume()
    }
    
    func request(withContextPath contextPath:String, withParameters parameters:[String: String]) -> URLRequest {
//        var allParameters = [
//            "client_id": "VN32D5EXSKJY2MSW3D1K4GL0MBSW1HAXUOYCGWHQUSWPZWUI",
//            "client_secret": "CEU4GLHBT25GVOIFRSOCMFDVOCDKHON0GJILGLPACQNHIV5Y",
//            "v":"20120609"
//        ]
//        allParameters += parameters
//        let parameterString = allParameters.parameterizedStringForServer()
        let parameterString = parameters.parameterizedStringForServer()
        let urlString = "\(basePath)\(contextPath)?\(parameterString)"
        print("aaaaaa: \(urlString)")
        
        return URLRequest(url: URL(string: urlString)!)
    }
}
